package com.pie4cloud.pie.job.biz.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pie4cloud.pie.jpa.BaseDao;
import com.pie4cloud.pie.jpa.BaseService;
import com.pie4cloud.pie.jpa.page.PageBean;
import com.pie4cloud.pie.jpa.page.PageForm;
import com.pie4cloud.pie.jpa.specification.SimpleSpecificationBuilder;
import com.pie4cloud.pie.job.api.entity.PlaybillEntity;
import com.pie4cloud.pie.job.biz.dao.PlaybillDao;
import com.pie4cloud.pie.job.biz.service.JobInfoService;
import com.pie4cloud.pie.job.biz.service.PlayBillService;
import com.pie4cloud.pie.job.biz.thread.ScheduleThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PlayBillServiceImpl extends BaseService<PlaybillEntity,Long> implements PlayBillService {
	@Autowired
	private PlaybillDao playbillDao;
	@Autowired
	private JobInfoService jobInfoService;
	@Autowired
	private ScheduleThread scheduleThread;
	@Override
	public BaseDao<PlaybillEntity,Long> getBaseDao() {
		return playbillDao;
	}
	@Override
	public PlaybillEntity getById(Long id) {
		return playbillDao.findById(id).get();
	}

	public PageBean<PlaybillEntity> page(Page page, PlaybillEntity playbillEntity) {
		SimpleSpecificationBuilder specificationBuilder = new SimpleSpecificationBuilder();
		Specification specification = specificationBuilder.generateSpecification();
		Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
		PageForm pageForm = new PageForm((int) page.getCurrent(), (int) page.getSize());
		PageBean pageBean = this.getPage(specification, pageForm, sort);
		return pageBean;
	}

	public PlaybillEntity save(PlaybillEntity playbillEntity){
		playbillEntity=playbillDao.saveNotNull(playbillEntity);
		playbillEntity.setType("PLAYBILL");
		playbillEntity.setIsManual(true);
		jobInfoService.start(playbillEntity);
		scheduleThread.handM(playbillEntity);
        return playbillEntity;
	}

	public PlaybillEntity update(PlaybillEntity playbillEntity){
		playbillEntity=playbillDao.saveNotNull(playbillEntity);
		playbillEntity.setIsManual(true);
		playbillEntity.setType("PLAYBILL");
		jobInfoService.start(playbillEntity);
		scheduleThread.handM(playbillEntity);
		return playbillEntity;
	}

	public Boolean removeById(Long id) {
		jobInfoService.stop(id);
		playbillDao.deleteById(id);
		return true;
	}

	public List<PlaybillEntity> findAll(){
		return playbillDao.findAll();
	}

	public PlaybillEntity findByDdataId(String ddataId){
		return playbillDao.findByDdataId(ddataId);
	}
}
